//
//  DoorLockUtil+Encrypt.swift
//  ZhiTing
//
//  Created by iMac on 2022/5/10.
//

import Foundation
import CryptoSwift

// MARK: - 数据加密解密
extension DoorLockUtil {
    func encrypt(data: Data) -> Data? {
        guard let pinData = doorLock?.pin else { return nil }
        let pin = Array(pinData)
        /// KEY
        let key = pin.md5()
            
        /// IV
        let iv = (key + pin).md5()
        
        do {
            let aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7)
            let encryptedData = try aes.encrypt(Array(data))
            return Data(encryptedData)
        } catch {
            return nil
        }
    }
    
    
    func decrypt(data: Data) -> Data? {
        guard let pinData = doorLock?.pin else { return nil }
        let pin = Array(pinData)
        /// KEY
        let key = pin.md5()
            
        /// IV
        let iv = (key + pin).md5()
        
        do {
            let aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs7)
            let decryptedData = try aes.decrypt(Array(data))
            return Data(decryptedData)
        } catch {
            return nil
        }
    }
}

